<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\CardHolder;
use App\Model\Cards;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Swagger\Annotations as SWG;

class CardHolderController extends Controller
{
    /**
     * @SWG\Get(
     *     path="/front/card/holder",
     *     tags={"用户相关"},
     *     summary="收藏的名片列表",
     *     description="收藏的名片列表",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="keyword", in="query", type="string", description="搜索"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="card_id", type="integer", description="名片id"),
     *                  @SWG\Property(property="user_id", type="integer", description="用户id"),
     *                  @SWG\Property(property="name", type="string", description="用户名"),
     *                  @SWG\Property(property="cover", type="string", description="头像"),
     *                  @SWG\Property(property="profession", type="string", description="职业"),
     *                  @SWG\Property(property="industry", type="string", description="行业"),
     *                  @SWG\Property(property="company", type="string", description="公司"),
     *                  @SWG\Property(property="phone", type="string", description="电话"),
     *                  @SWG\Property(property="wechat", type="string", description="微信号"),
     *                  @SWG\Property(property="address", type="string", description="地址"),
     *                  @SWG\Property(property="vip_level", type="string", description="vip等级"),
     *              )
     *          )
     *      )
     * )
     */
    public function index()
    {
        $holders = CardHolder::select('card_holders.id','card_holders.card_id','cards.head_picture','cards.profession','cards.industry','cards.company','card_holders.created_at','cards.user_name','cards.user_id', 'cards.mobile_phone', 'cards.wechat_code', 'vf.type', 'cards.address_detail', 'cards.style')
            ->leftJoin('cards','card_holders.card_id','=','cards.id')
            ->leftJoin('user_grade as ug', function($join) {
                $join->on('ug.user_id', '=', 'cards.user_id')->where('overed_at', '>', Carbon::now());
            })
            ->leftJoin('vip_fee_config as vf', 'vf.id', '=', 'ug.vip_fee_config_id')
            ->where('card_holders.user_id', Auth::id())
            ->when(request('keyword'), function($query) {
            $query->where('cards.user_name', 'like', '%'.\request('keyword').'%');
        })->orderByDesc('card_holders.created_at')->paginate(\request('limit', 10));
        $data = [];
        foreach ($holders as $holder){
            $data[] = [
                'id' => $holder['id'],
                'card_id' => $holder['card_id'],
                'user_id' => $holder['user_id'],
                'name' => $holder['user_name'],
                'cover' => $holder['head_picture'],
                'profession' => $holder['profession'],
                'industry' => $holder['industry'],
                'company' => $holder['company'],
                'created_at' => $holder['created_at']->format('Y-m-d H:i:s'),
                'phone' => $holder['mobile_phone'],
                'wechat' => $holder['wechat_code'],
                'address' => $holder['address_detail'],
                'vip_level' => $holder['type']?:0,
                'style' => $holder['style']
            ];
        }
        return $this->renderJson($data);
    }

    /**
     * @SWG\Get(
     *     path="/front/card/holder/page",
     *     tags={"用户相关"},
     *     summary="收藏的名片列表(手动分页)",
     *     description="收藏的名片列表",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="offset", in="query", type="integer", description="偏移"),
     *     @SWG\Parameter(name="limit", in="query", type="integer", description="步长"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              @SWG\Property(
     *                  property="data",
     *                  type="array",
     *                  @SWG\Items(
     *                      @SWG\Property(property="id", type="integer", description="id"),
     *                      @SWG\Property(property="card_id", type="integer", description="名片id"),
     *                      @SWG\Property(property="user_id", type="integer", description="用户id"),
     *                      @SWG\Property(property="name", type="string", description="用户名"),
     *                      @SWG\Property(property="cover", type="string", description="头像"),
     *                      @SWG\Property(property="profession", type="string", description="职业"),
     *                      @SWG\Property(property="industry", type="string", description="行业"),
     *                      @SWG\Property(property="company", type="string", description="公司"),
     *                  )
     *              ),
     *              @SWG\Property(property="count", type="integer", description="总数")
     *          )
     *      )
     * )
     */
    public function page()
    {
        $user_id = Auth::id();
        $holdersM = CardHolder::select('card_holders.id','card_holders.card_id','cards.head_picture','cards.profession','cards.industry','cards.company','card_holders.created_at','cards.user_name','cards.user_id', 'cards.style', 'cards.mobile_phone', 'cards.wechat_code', 'cards.address_detail')
            ->join('cards','card_holders.card_id','=','cards.id')
            ->where('card_holders.user_id', $user_id);
        if (request('keyword')) {
            $holdersM->where('cards.user_name', 'like', request('keyword') . '%');
        }
        $holdersM->orderByDesc('card_holders.created_at');
        $count = $holdersM->count();
        $holders = $holdersM
            ->offset(request('offset', 1))
            ->limit(request('limit', 10))
            ->get();
        $data['data'] = [];
        foreach ($holders as $holder){
            $data['data'][] = [
                'id' => $holder['id'],
                'card_id' => $holder['card_id'],
                'user_id' => $holder['user_id'],
                'name' => $holder['user_name'],
                'cover' => $holder['head_picture'],
                'profession' => $holder['profession'],
                'industry' => $holder['industry'],
                'company' => $holder['company'],
                'created_at' => $holder['created_at']->format('Y-m-d H:i:s'),
                'vip_level' => User::is_vip($holder['user_id']),
                'style' => $holder['style'],
                'phone' => $holder['mobile_phone'],
                'wechat' => $holder['wechat_code'],
                'address' => $holder['address_detail'],
            ];
        }
        $data['count'] = $count;
        return $this->renderJson($data);
    }

    /**
     *
     * @SWG\Post(
     *     path="/front/card/holder",
     *     tags={"用户相关"},
     *     summary="添加名片",
     *     description="添加名片",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="card_id", in="formData", required=true, type="integer", description="名片id"),
     *     @SWG\Response(
     *         response=200,
     *         description="操作成功"
     *     )
     * )
     */
    public function store(Request $request, CardHolder $holder)
    {
        $user_id = $request->user()->id;
        $this->validate($request, [
            'card_id' => 'required'
        ], [
            'required' => ':attribute不能为空'
        ], [
            'card_id' => '名片id'
        ]);
        $card_id = $request->input('card_id');
        //2018.8.15 新增非会员只能收藏10次
        if (!User::is_vip(Auth::id())){
            $n = CardHolder::where('user_id', $request->user()->id)->count();
            if ($n >= 10){
                return $this->fail('开通会员，无限收藏哦!');
            }
        }
        $card = Cards::findOrFail($card_id);
        $count = CardHolder::where('user_id',$user_id)->where('card_id',$card->id)->count();
        if ($count >= 1){
            return $this->fail('你已经添加过该名片了');
        }
        if ($card->user_id == $user_id){
            return $this->fail('不能收藏自己');
        }
        $holder->user_id = $user_id;
        $holder->card_id = $card->id;
        if ($holder->save()) {
            //添加保存
            $card->increment('saved');
            $card->save();
            return $this->success();
        }
        return $this->error('添加失败');
    }

    /**
     * @SWG\Delete(
     *     path="/front/card/holder",
     *     tags={"用户相关"},
     *     summary="删除名片夹",
     *     description="删除名片夹",
     *     consumes={"application/x-www-form-urlencoded"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="ids", in="formData", type="string", description="ids"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="string", description="id"),
     *     @SWG\Response(
     *          response="200",
     *          description="操作成功"
     *      )
     * )
     */
    public function destroy()
    {

        $ids = \request('ids');
        $holder = CardHolder::whereIn('card_id',$ids)->where('user_id', Auth::id())->get();
        if (empty($holder)){
            return $this->fail('你还没有收藏');
        }
        try {
            foreach ($holder as $item) {
                $card = Cards::find($item->card_id);
                $card->decrement('saved');
                $item->delete();
            }

        } catch (\Exception $e) {
            \Log::error($e);
            return $this->error();
        }

        return $this->success();
    }

    /**
     * @SWG\Get(
     *     path="/front/card/holder/record",
     *     tags={"用户相关"},
     *     summary="那些人收藏了我",
     *     description="那些人收藏了我",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="user_id", type="integer", description="用户"),
     *                  @SWG\Property(property="card_id", type="integer", description="对方名片"),
     *                  @SWG\Property(property="page_type", type="integer", description="网页类型"),
     *                  @SWG\Property(property="name", type="string", description="用户名"),
     *                  @SWG\Property(property="cover", type="string", description="头像"),
     *                  @SWG\Property(property="company", type="string", description="公司"),
     *              )
     *          )
     *      )
     * )
     */
    public function record()
    {
        //非会员不能查看
        if (!User::is_vip(Auth::id())){
            return $this->fail('开通会员才能查看哦');
        }
        $id = Cards::where('user_id', Auth::id())->pluck('id')->first();
        if (empty($id)){
            return $this->renderJson();
        }

        $row = DB::table('card_holders as ch')
            ->select('ch.user_id', 'c.id as card_id','c.user_name', 'u.wechat_name', 'c.head_picture', 'u.head_portrait', 'ch.created_at', 'pu.type as page_type', 'c.company')
            ->leftJoin('cards as c', 'c.user_id', '=', 'ch.user_id')
            ->leftJoin('user_detail as u', 'u.user_id', '=', 'ch.user_id')
            ->leftJoin('personal_page_template_user as pu','pu.id', '=',  DB::raw('(SELECT MAX(id) from personal_page_template_user where user_id=ch.user_id)'))
            ->where('ch.card_id', $id)
            ->orderByDesc('ch.created_at')
            ->paginate(\request('limit', 10));


        $data = $row->toArray();
        $items = collect($data['data']);
        $items = $items->map(function ($item) {
            $item = collect($item)->toArray();
            $item['name'] = $item['user_name']?:$item['wechat_name'];
            $item['portrait'] = $item['head_picture']?:$item['head_portrait'];
            unset($item['user_name']);
            unset($item['wechat_name']);
            unset($item['head_picture']);
            unset($item['head_portrait']);
            return $item;
        });
        $data['data'] = $items;
        return $this->renderJson($data);
    }
}
